//
//  YLCTabBarViewController.m
//  YouLe
//
//  Created by 初程程 on 2018/1/5.
//  Copyright © 2018年 初程程. All rights reserved.
//

#import "YLCTabBarViewController.h"
#import "YLCTabbar.h"
#import "YLCNavigationViewController.h"
#import "AppDelegate.h"
#import "YLCBaseSendViewController.h"
#import "YLCSendGoodsViewController.h"
#import "YLCSendViewController.h"
#import "YLCSendQuestionViewController.h"
#import "YLCSendTrainViewController.h"
#import "HWVideoVC.h"
#import "YLCSendJobViewController.h"
#import "ShootVideoViewController.h"
#import "YLCSendVideoNextViewController.h"

@interface YLCTabBarViewController ()<UITabBarControllerDelegate,YLCBaseSendViewControllerDelegate>

@end

@implementation YLCTabBarViewController
{
    YLCTabbar *tabbar;
}
- (void)hiddenRed{
    [tabbar hiddenRed];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setTabbar];
}
- (void)getUnreadCount{
    [tabbar getUnreadCount];
}
- (void)setTabbar{
    
    tabbar = [[YLCTabbar alloc]init];
    
    [tabbar didselectedIrrBtnWithBlock:^{
        
        if (![YLCLoginManager checkLoginStateWithTarget:self]) {
            return ;
        }
        [self gotoSend];
//        [self setSelectedIndex:2];
    }];
    
    [self setValue:tabbar forKey:@"tabBar"];
    
}

- (void)gotoSend{
    YLCBaseSendViewController *con = [[YLCBaseSendViewController alloc] init];
    
    con.delegate = self;
    
    YLCNavigationViewController *nav = [[YLCNavigationViewController alloc] initWithRootViewController:con];
    
    [self presentViewController:nav animated:NO completion:nil];
}
- (void)gotoSendDetist{
    YLCSendViewController *con  = [[YLCSendViewController alloc] init];
    
    [(UINavigationController *)self.selectedViewController pushViewController:con animated:YES];
}
- (void)didSelectAtIndex:(NSInteger)index{
    if (index==0) {
        [self gotoSendDetist];
    }
    if (index==1) {
        [self gotoSendQuestion];
    }
    if (index==2) {
        [self gotoGoods];
    }
    if (index==3) {
        [self sendJob];
    }
    if (index==4) {
        [self gotoSendTrainWithType:0];
    }
    if (index==5) {
        [self gotoSendTrainWithType:1];
    }
    if (index==6) {
        [self videoRecord];
    }
    if (index==7) {
        [self albumRecord];
    }
}
- (void)albumRecord{
    
    HXAlbumListViewController *con = [[HXAlbumListViewController alloc] init];
    
    HXPhotoManager *manager = [[HXPhotoManager alloc] initWithType:HXPhotoManagerSelectedTypeVideo];
    manager.configuration.openCamera = NO;
    
    manager.configuration.photoMaxNum = 1;
    
    con.manager = manager;
    
    con.doneBlock = ^(NSArray<HXPhotoModel *> *allList, NSArray<HXPhotoModel *> *photoList, NSArray<HXPhotoModel *> *videoList, BOOL original, HXAlbumListViewController *viewController) {
        HXPhotoModel *photoModel = videoList[0];
        [self getVideoFromPHAsset:photoModel.asset photoModel:photoModel];
    };
    
    if (self.presentedViewController != nil) {
        [(UINavigationController *)self.selectedViewController dismissViewControllerAnimated:NO completion:nil];
    }
    HXCustomNavigationController *nav = [[HXCustomNavigationController alloc] initWithRootViewController:con];
    
    [(UINavigationController *)self.selectedViewController presentViewController:nav animated:YES completion:nil];
}
- (void)getVideoFromPHAsset:(PHAsset *)asset
                 photoModel:(HXPhotoModel *)photoModel{
    NSArray *assetResources = [PHAssetResource assetResourcesForAsset:asset];
    PHAssetResource *resource;
    
    for (PHAssetResource *assetRes in assetResources) {
        if (@available(iOS 9.1, *)) {
            if (assetRes.type == PHAssetResourceTypePairedVideo ||
                assetRes.type == PHAssetResourceTypeVideo) {
                resource = assetRes;
            }
        } else {
            // Fallback on earlier versions
        }
    }
    NSString *fileName = @"tempAssetVideo.mov";
    if (resource.originalFilename) {
        fileName = resource.originalFilename;
    }
    
    PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
    
    options.version = PHImageRequestOptionsVersionCurrent;
    
    options.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic;
    
    PHImageManager *manager = [PHImageManager defaultManager];
        
    NSDateFormatter *formater = [[NSDateFormatter alloc] init];//用时间给文件全名，以免重复
    [formater setDateFormat:@"yyyyMMddHHmmss"];
    NSString *nowTimeStr = [formater stringFromDate:[NSDate dateWithTimeIntervalSinceNow:0]];
    NSString *fileNames = [nowTimeStr stringByAppendingString:@"merge.mp4"];
    NSString *PATH_MOVIE_FILE_MP4 = [NSTemporaryDirectory() stringByAppendingPathComponent:fileNames];
    
    [[NSFileManager defaultManager] removeItemAtPath:PATH_MOVIE_FILE_MP4 error:nil];
    
    [manager requestExportSessionForVideo:asset options:options exportPreset:AVAssetExportPresetMediumQuality resultHandler:^(AVAssetExportSession * _Nullable exportSession, NSDictionary * _Nullable info) {
        exportSession.outputURL = [NSURL fileURLWithPath:PATH_MOVIE_FILE_MP4];
        exportSession.shouldOptimizeForNetworkUse = YES;
        exportSession.outputFileType = AVFileTypeMPEG4;
        [exportSession exportAsynchronouslyWithCompletionHandler:^{
            
            if ([exportSession status] == AVAssetExportSessionStatusCompleted) {
                
                dispatch_async(dispatch_get_main_queue(),^{
                    YLCSendVideoNextViewController *con = [[YLCSendVideoNextViewController alloc] init];
                    con.videoPath = photoModel.fileURL;
                    con.isAlbum = YES;
                    con.mp4VideoPath = PATH_MOVIE_FILE_MP4;
                    CGFloat f = [self getFileSize:PATH_MOVIE_FILE_MP4];
                    NSLog(@"相册选择视频大小：%f",f);
                    [(UINavigationController *)self.selectedViewController pushViewController:con animated:YES];
                });
            }
        }];
    }];
}
- (CGFloat) getFileSize:(NSString *)path{
    NSLog(@"%@",path);
    NSFileManager *fileManager = [NSFileManager defaultManager];
    float filesize = -1.0;
    if ([fileManager fileExistsAtPath:path]) {
        NSDictionary *fileDic = [fileManager attributesOfItemAtPath:path error:nil];//获取文件的属性
        unsigned long long size = [[fileDic objectForKey:NSFileSize] longLongValue];
        filesize = 1.0*size/1024;
    }else{
        NSLog(@"找不到文件");
    }
    return filesize;
}
- (void)sendJob{
    YLCSendJobViewController *con = [[YLCSendJobViewController alloc] init];
    
    [(UINavigationController *)self.selectedViewController pushViewController:con animated:YES];

}
- (void)videoRecord{
    
    ShootVideoViewController *con = [[ShootVideoViewController alloc] init];
    
    YLCNavigationViewController *nav  = [[YLCNavigationViewController alloc] initWithRootViewController:con];
    
    if (self.presentedViewController != nil) {
        [(UINavigationController *)self.selectedViewController dismissViewControllerAnimated:NO completion:nil];
    }
    [self presentViewController:nav animated:YES completion:nil];
}
- (void)gotoSendQuestion{
    
    YLCSendQuestionViewController *con = [[YLCSendQuestionViewController alloc] init];
    
    [(UINavigationController *)self.selectedViewController pushViewController:con animated:YES];

}
- (void)gotoGoods{
    YLCSendGoodsViewController *con = [[YLCSendGoodsViewController alloc] init];
    
    [(UINavigationController *)self.selectedViewController pushViewController:con animated:YES];
}
- (void)gotoSendTrainWithType:(NSInteger)type{
    YLCSendTrainViewController *con = [[YLCSendTrainViewController alloc] init];
    
    con.sendType = type;
    
    [(UINavigationController *)self.selectedViewController pushViewController:con animated:YES];
}
- (void)setSelectedIndex:(NSUInteger)selectedIndex{
    [super setSelectedIndex:selectedIndex];
    
    YLCTabBarViewController *tabbar = (YLCTabBarViewController *)[AppDelegate appDelegate].window.rootViewController;
    
    YLCNavigationViewController *nav = tabbar.selectedViewController;
    
    [self tabBarController:tabbar didSelectViewController:nav];
}
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
    
    [(YLCNavigationViewController *)viewController popToRootViewControllerAnimated:NO];
//    self.tabBar.hidden = NO;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
